package election.platform;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.HashMap;
import java.util.Map;

import election.api.OpSpawn;


public class LocalService implements Runnable
{
    Map<String,OpSpawn>     ops = new HashMap<String,OpSpawn>();
    {
        //ops.put("ReportIP", new ReportIP());
    }
    
    DatagramSocket socket;
    DatagramPacket packet;
    MyQueue queue = new MyQueue();
    
    public LocalService(int port) throws Exception
    {
        socket = new DatagramSocket(port);
        packet = new DatagramPacket(new byte[1024],1024);
    }

    protected void processOne() throws Exception
    {
        // receive an Op request
        packet.setLength(1024);
        socket.receive(packet);
        String opName = new String(packet.getData(),0,packet.getLength(),"UTF-8");
        if (opName.equals("ReportIP")) {
            socket.send(packet);
            return;
        }
//        OpSpawn op = ops.get(opName);
//        op.apply(queue);
//        
//        // process the Op and send result back (assume only a single byte[] is returned)
//        byte[] toSend = (byte[])queue.get();
//        if (toSend == null || toSend.length == 0)
//            return;
//        System.arraycopy(toSend, 0, packet.getData(), 0, toSend.length);
//        packet.setLength(toSend.length);
//        socket.send(packet);
    }
    
    @Override
    public void run()
    {
        while (true) try {
            processOne();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
